package com.fleafinder;

import java.io.IOException;
import java.io.InputStream;
import java.net.MalformedURLException;
import java.net.SocketTimeoutException;
import java.net.URL;
import java.net.URLEncoder;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.Formatter;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Locale;
import java.util.Map;

import org.xmlpull.v1.XmlPullParserException;

import android.app.Activity;
import android.app.ProgressDialog;
import android.content.Context;
import android.graphics.Point;
import android.location.Address;
import android.location.Geocoder;
import android.os.AsyncTask;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.util.SparseArray;

import com.fleafinder.entity.Category;
import com.fleafinder.entity.Market;
import com.fleafinder.entity.MarketType;
import com.fleafinder.xmlparser.CategoryXmlParser;
import com.fleafinder.xmlparser.MarketTypeXmlParser;
import com.fleafinder.xmlparser.MarketXmlParser;
import com.google.android.gms.maps.model.LatLng;

public class DataCenter {
	private static DataCenter dataCenter;

	private List<MarketType> marketTypeList;
	private List<Category> categoryList;
	private List<Market> marketList;
	private List<Market> businessMarketList;
	private List<Market> marketListWithLoadedLocation;

	/**
	 * This contains a list of loaded Market for screen Market Info.<br/>
	 * Whenever there is a request to load a Market with MarketID = x,
	 * DataCenter will look inside this Array to find if the Market is loaded
	 * and reuse it. This saves time and CPU over retrieving the data from
	 * website whenever there is request.<br/>
	 * But if the <code>loadedTime</code> inside each Market is greater than
	 * {@link CommonConstants#TIME_INTERVAL_TO_RELOAD_MARKET} then the Market
	 * should reloaded ensure the Market stays updated with data from website.
	 */
	private SparseArray<Market> marketInfoArray;

	private Map<MarketType, List<Market>> dataOrganized;

	private boolean isLoadingMarketList = true;
	private boolean isLoadingMarketTypeList = true;
	private boolean isLoadingBusinessMarketList = true;
	private boolean isRootFragmentOfTab = false;
	
	private boolean isLoadingMarketLocation = true;
	private int timesOfLoadingLocation = 0;
	
	public boolean isLoadingBusinessMarket() {
		return isLoadingBusinessMarketList;
	}

	private DateFormat dateFormat;

	private Date lastTimeLoadData;

	private DataUser currentDataUser;

	/**
	 * For screen "Market List", when user clicks any Market in the list to view
	 * Market Details. Please set that selected to this variable so that screen
	 * "Market Details" can trace & get some info to build the layout.
	 */
	private Market selectedMarketForDetailsView = null;

	private MapScreenFragmentContainer mapScreenFragmentContainer = null;
	private MapScreenFragment mapScreenFragment = null;

	private OpenMarketFragment openMarketFragment = null;

	private HomeScreenFragment homeScreenFragment = null;

	/**
	 * Screen for reuse -> no need to init a new instance which consumes much
	 * resource
	 */
	private MarketDetailsFragment marketDetailsFragment = null;

	private MarketDetailsFragment marketDetailsFragmentForTopMarkeder = null;

	private MarketDetailsFragment marketDetailsFragmentForMap = null;

	private MarketListFragment marketListFragment = null;
	
	private MarketListFragment marketListFragmentForTopMarkeder = null;

	private MarketListFragment topMarketFragment = null;
	
	private CategoryListFragment categoryListFragment = null;

	private boolean threadLoadMarketListDone = false;

	private Context context = null;

	private Handler messageHandler = new Handler() {

		@Override
		public void handleMessage(Message msg) {
			currentDataUser.updateLayout();
		}

	};

	private int selectedmarketType;
	private int selectedMaketCategory;
	private int currentMarketListMode;
	private int currentSelectedTab;
	private int saveCurrentMarketListMode;

	private Geocoder geocoder;
	
	private Point screenSize;
	
	private LatLng deviceCurrentLocation = null;

	private DataCenter() {
		int smallSeed = 20, bigSeed = 50;

		marketTypeList = new ArrayList<MarketType>(smallSeed);
		categoryList = new ArrayList<Category>(smallSeed);
		marketList = new ArrayList<Market>(bigSeed);
		businessMarketList = new ArrayList<Market>(bigSeed);
		marketListWithLoadedLocation = new ArrayList<Market>(smallSeed);
		dataOrganized = new HashMap<MarketType, List<Market>>();

		marketInfoArray = new SparseArray<Market>(smallSeed);

		dateFormat = new SimpleDateFormat(CommonConstants.DATE_FORMAT);
	}

	public static DataCenter getInstance() {
		if (dataCenter == null) {
			dataCenter = new DataCenter();
		}

		return dataCenter;
	}

	public void startLoadingData() {
		Thread threadMarketTypeAndCategory = new Thread(
				"threadMarketTypeAndCategory") {

			@Override
			public void run() {
				readMarketTypeListFromWebsite();
				isLoadingMarketTypeList = false;

				for (MarketType mt : marketTypeList) {
					dataOrganized.put(mt, new ArrayList<Market>());
				}

				readCategoryListFromWebsite();
			}

		};
		threadMarketTypeAndCategory.start();

		Thread threadMarkets = new Thread("threadMarkets") {

			@Override
			public void run() {

				int pageNum = 0;
				int oldMarketListSize = -1;
				int lastCheckMarketTypeStoppedAt = 0;
			
				// lastCheckMarketTypeStoppedAt = 0;

				while (oldMarketListSize != businessMarketList.size()) {
					oldMarketListSize = businessMarketList.size();
					readBusinessMarketListFromWebsite(
							CommonConstants.DEFAULT_PAGE_SIZE, ++pageNum);
				}
				/*for(int i = 0;i < 50; i++){
					Market m = new Market();
					m.setName("name " + i);
					m.setRoad("road");
					m.setMarketTypeName("marketTypeName");
					m.setCity("city");
					m.setZip("zip");
					m.setDateFrom("dateFrom");
					m.setDateTo("dateTo");
					m.setStande("stande");
					m.setStartAt("startAt");
					m.setEndAt("endAt");
					businessMarketList.add(m);
				}*/
				isLoadingBusinessMarketList = false;
				
				pageNum = 1;
				oldMarketListSize = -1;
				while (oldMarketListSize != marketList.size()) {
					oldMarketListSize = marketList.size();
					readMarketListFromWebsite(
							CommonConstants.DEFAULT_PAGE_SIZE, pageNum++);
//					Log.d("", "Old market list size: " + oldMarketListSize);
//					Log.d("", "New market list size: " + marketList.size());
//					Log.d("debug", "Market List is @" + marketList);
					lastTimeLoadData = new Date();

					if (isLoadingMarketTypeList) {
						try {
							Thread.sleep(CommonConstants.DEFAULT_SLEEP_TIME);
						} catch (InterruptedException e) {
							// e.printStackTrace();
//							Log.i("1", e.getMessage());
						}
					}

					// set the correct MarketType to Market->marketType
					// if (!isLoadingMarketTypeList) {
					int currentMarketListSize = marketList.size();
					for (int i = lastCheckMarketTypeStoppedAt; i < currentMarketListSize; ++i) {
						for (MarketType mt : marketTypeList) {
							if (mt.getMarketTypeName().equals(
									marketList.get(i).getMarketTypeName())) {
								marketList.get(i).setMarketType(mt);

								// add Market to dataOrganized
								dataOrganized.get(mt).add(marketList.get(i));

								// add Market to businessMarketList
								/*
								 * if(marketList.get(i).getFeeType().contains(
								 * CommonConstants.PLUS_SIGN)){
								 * addMarketToMarketListInSortedManner
								 * (marketList.get(i), businessMarketList); }
								 */

								break;
							}
						}
					}
					lastCheckMarketTypeStoppedAt = currentMarketListSize;
					// }
				}// end of reading market list

				// ------- this is to read business market list
				// ------- this code is duplicated and will be improved in
				// future
				
				
				// this code move here to ensure Mrtket-List and Top-Market were
				// loaded
				// set the flag threadLoadMarketListDone here
				// 2 cases:
				// 1. user open Market list after threadLoadMarketListDone =
				// true -> in the method getMarketList() {return marketList;}
				// 2. user open Market list after threadLoadMarketListDone NOT
				// YET = true -> in the method getMarketList() {return new
				// marketList with size = 20;}
				// and fire event here
				threadLoadMarketListDone = true;
				// if (marketListFragment != null) {
				// marketListFragment.getListViewMarketListAdapter()
				// .notifyDataSetChanged();
				// }

			}// end of method run

		};
		threadMarkets.start();
		
		startThreadLoadingMarketLocation();
//		Log.v("1", "STARTED loading Market Location");
	}

	public void readMarketTypeListFromWebsite() {
		if (!marketTypeList.isEmpty()) {
			return;
		}
		URL url;
		try {
			url = new URL(CommonConstants.LINK_MARKET_TYPE_LIST);
			InputStream stream = url.openStream();
			MarketTypeXmlParser parser = new MarketTypeXmlParser();
			parser.parse(stream);
			marketTypeList = parser.getMarketTypeList();
		} catch (MalformedURLException e) {
			Log.d("1", e.getMessage());
		} catch (IOException e) {
			Log.d("2", e.getMessage());
		} catch (XmlPullParserException e) {
			Log.d("3", e.getMessage());
		}
	}

	public void readCategoryListFromWebsite() {
		if (!categoryList.isEmpty()) {
			return;
		}
		URL url;
		try {
			url = new URL(CommonConstants.LINK_CATEGORY_LIST);
			InputStream stream = url.openStream();
			CategoryXmlParser parser = new CategoryXmlParser();
			parser.parse(stream);
			categoryList = parser.getCategoryList();
		} catch (MalformedURLException e) {
			Log.d("1", e.getMessage());
		} catch (IOException e) {
			Log.d("2", e.getMessage());
		} catch (XmlPullParserException e) {
			Log.d("3", e.getMessage());
		}
	}

	public void readMarketListFromWebsite(int pageSize, int pageNum) {
//		Log.i("1", "Read Market List from website: Pagesize = " + pageSize
//				+ "; PageNum = " + pageNum);
		URL url;
		try {
			url = new URL(new Formatter().format(CommonConstants.LINK_VIEW_ALL,
					pageSize, pageNum).toString());
			InputStream stream = url.openStream();
			MarketXmlParser parser = new MarketXmlParser(marketList);
			parser.parse(stream);
		} catch (MalformedURLException e) {
			Log.d("1", e.getMessage());
		} catch (IOException e) {
			Log.d("2", e.getMessage());
		} catch (XmlPullParserException e) {
			Log.d("3", e.getMessage());
		}

		isLoadingMarketList = false;
	}

	public void readBusinessMarketListFromWebsite(int pageSize, int pageNum) {

		URL url;
		try {
			url = new URL(new Formatter().format(
					CommonConstants.LINK_TOP_MARKEDERS, pageSize, pageNum)
					.toString());
			InputStream stream = url.openStream();
			MarketXmlParser parser = new MarketXmlParser(businessMarketList);
			parser.parse(stream);
		} catch (MalformedURLException e) {
			Log.d("1", e.getMessage());
		} catch (IOException e) {
			Log.d("2", e.getMessage());
		} catch (XmlPullParserException e) {
			Log.d("3", e.getMessage());
		}

		isLoadingBusinessMarketList = false;
	}

	public void startReadMoreMarketListFromWebsite(DataUser dataUser) {
		if (lastTimeLoadData == null) {
			return;
		}

		currentDataUser = dataUser;

		Thread threadReadMoreMarkets = new Thread("Thread Read More Markets") {
			@Override
			public void run() {
				removeOutOfDateMarkets(marketList);
				removeOutOfDateMarkets(businessMarketList);
				removeOutOfDateMarkets(marketListWithLoadedLocation);
				Iterator<MarketType> keys = dataOrganized.keySet().iterator();
				MarketType mt = null;

				while (keys.hasNext()) {
					mt = keys.next();
					removeOutOfDateMarkets(dataOrganized.get(mt));
				}

				List<Market> tempMarketList = new ArrayList<Market>()/*
																	 * ,
																	 * businessTempList
																	 * = new
																	 * ArrayList
																	 * <
																	 * Market>()
																	 */;

				String param = URLEncoder.encode(new Formatter().format(
						CommonConstants.LINK_LOAD_NEW_MARKETS_PARAM,
						lastTimeLoadData.getYear(),
						lastTimeLoadData.getMonth(),
						lastTimeLoadData.getDate(),
						lastTimeLoadData.getHours(),
						lastTimeLoadData.getMinutes(),
						lastTimeLoadData.getSeconds()).toString());
				URL url = null;
				try {
					url = new URL(new Formatter().format(
							CommonConstants.LINK_LOAD_NEW_MARKETS, param)
							.toString());
					MarketXmlParser parser = new MarketXmlParser(tempMarketList);
					parser.parse(url.openStream());

					addMarketsToMarketListInSortedManner(tempMarketList,
							marketList);

					// add Market to businessMarketList
					for (Market m : tempMarketList) {
						/*
						 * if(m.getFeeType().contains(CommonConstants.PLUS_SIGN))
						 * { addMarketToMarketListInSortedManner(m,
						 * businessMarketList); }
						 */

						// set the correct MarketType to Market->marketType
						for (MarketType mkt : marketTypeList) {
							if (mkt.getMarketTypeName().equals(
									m.getMarketTypeName())) {
								m.setMarketType(mkt);

								// add Market to dataOrganized
								addMarketToMarketListInSortedManner(m,
										dataOrganized.get(mkt));
								break;
							}
						}
					}

					Message msg = Message.obtain();
					messageHandler.sendMessage(msg);

				} catch (MalformedURLException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				} catch (XmlPullParserException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				} catch (IOException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
			}
		};
		threadReadMoreMarkets.start();
	}

	/**
	 * This returns a Market with details.<br/>
	 * This searches locally to find an-already-loaded-Market with same ID.<br/>
	 * If no any Market found OR the loaded time of that
	 * an-already-loaded-Market is greater than
	 * {@link CommonConstants#TIME_INTERVAL_TO_RELOAD_MARKET} then this method
	 * will reload the Market from website to ensure data is updated.
	 * 
	 * @param markedId
	 * @return
	 */
	public Market readMarkedInfo(int markedId) {
		Market temp = null;

//		Log.i("1", "Read Market Info from website: MarkedID = )" + markedId);
		URL url;
		try {
			Date d = new Date();
			temp = marketInfoArray.get(markedId);
			if (temp != null) {
				if (d.getTime() - temp.getLoadedTime().getTime() < CommonConstants.TIME_INTERVAL_TO_RELOAD_MARKET) {
					return temp;
				}
			}

			url = new URL(new Formatter().format(
					CommonConstants.LINK_MARKET_INFO, markedId).toString());
			InputStream stream = url.openStream();
			MarketXmlParser parser = new MarketXmlParser();
			parser.parse(stream);

			temp = parser.getParsedMarket();
			if(temp == null){
				
			} else {
				temp.setLoadedTime(d);

				marketInfoArray.put(markedId, temp);
			}
		} catch (MalformedURLException e) {
			Log.d("1", e.getMessage());
		} catch (IOException e) {
			Log.d("2", e.getMessage());
		} catch (XmlPullParserException e) {
			Log.d("3", e.getMessage());
		}

		return temp;
	}

	
	public int getTimesOfLoadingLocation() {
		return timesOfLoadingLocation;
	}

	public void startThreadLoadingMarketLocation(){
		isLoadingMarketLocation = true;
		timesOfLoadingLocation++;
		
		Thread threadLoadLocation = new Thread("threadLoadLocation") {
			@Override
			public void run() {
				getLocationForMarketList(marketList);
			}
		};
		threadLoadLocation.start();
	}
	
	/**
	 * 
	 * @param list
	 */
	public void getLocationForMarketList(List<Market> list) {
		int stoppedAt = 0, newSize = 0;
		Market m = null;

		boolean allLoaded = false;
		
		Geocoder gc = new Geocoder(context, Locale.getDefault());

		while (isLoadingMarketList || !allLoaded) {
			allLoaded = !isLoadingMarketList;
			newSize = list.size();
			for (int i = stoppedAt; i < newSize; ++i) {

				m = list.get(i);
				if (m.isShowOnMap()) {
					try {

						List<Address> listAddress = gc.getFromLocationName(
								m.getRoad() + ", " + m.getCity() + ", "
										+ CommonConstants.COUNTRY, 1);
						if (listAddress.size() == 0) {
							continue;
						}
						Address address = listAddress.get(0);
						m.setLongitude(address.getLongitude());
						m.setLatitude(address.getLatitude());
						m.setLoadedLocation(true);
						marketListWithLoadedLocation.add(m);
						
//						Log.d("location", "Market Location: " + m.getName() + "; Lng: " + m.getLongitude() + " - Lat: " + m.getLatitude());
						
					} catch (MalformedURLException e) {
						// TODO Auto-generated catch block
						e.printStackTrace();
					} catch (SocketTimeoutException e) {
						e.printStackTrace();
					} catch (IOException e) {
						// TODO Auto-generated catch block
						e.printStackTrace();
					}
				}

				//stoppedAt = i + 1;
			}// finish loading location for all markets in the marketList
			stoppedAt = newSize;
			// If this thread reaches here before all markets have been loaded
			// from website
			// then it is necessary to wait for the marketList to be fully
			// initialized and
			// continue to load locations.
			try {
				Thread.sleep(CommonConstants.DEFAULT_SLEEP_TIME);
			} catch (InterruptedException ex) {
				Log.i(ex.getMessage(), "");
			}
		}

		// finish loading location
		isLoadingMarketLocation = false;
	}

	/**
	 * If you load data at 11:40PM, the he uses the app to 00:20AM of the next
	 * morning => the date is now should be increased by 1. Then the app needs
	 * to check if some Markets have become unavailable (the current date passed
	 * its DateTo).
	 */
	public void removeOutOfDateMarkets(List<Market> list) {
		Market m;
		Date now = new Date();

		for (int i = list.size() - 1; i >= 0; --i) {
			m = list.get(i);

			if (m.getDateToObject().getYear() < now.getYear()) {
				list.remove(i);
			} else if (m.getDateToObject().getYear() == now.getYear()) {
				if (m.getDateToObject().getMonth() < now.getMonth()) {
					list.remove(i);
				} else if (m.getDateToObject().getMonth() == now.getMonth()) {
					if (m.getDateToObject().getDate() < now.getDate()) {
						list.remove(i);
					}
				}
			}
		}
	}

	/**
	 * 
	 * @param list
	 */
	public void formatDateOfMarkets(List<Market> list) {
		for (Market m : list) {
			formatDateOfMarket(m);
		}
	}

	/**
	 * 
	 * @param m
	 */
	public void formatDateOfMarket(Market m) {
		Date now = new Date();

		if (m.getDateFromObject().getYear() == now.getYear()
				&& m.getDateFromObject().getMonth() == now.getMonth()) {
			if (m.getDateFromObject().getDate() == now.getDate()) {
				m.setDateFrom(CommonConstants.TXT_TODAY);
			} else if (m.getDateFromObject().getDate() - now.getDate() == 1) {
				m.setDateFrom(CommonConstants.TXT_TOMORROW);
			}
		}

		if (m.getDateToObject().getYear() == now.getYear()
				&& m.getDateToObject().getMonth() == now.getMonth()) {
			if (m.getDateToObject().getDate() == now.getDate()) {
				m.setDateTo(CommonConstants.TXT_TODAY);
			} else if (m.getDateToObject().getDate() - now.getDate() == 1) {
				m.setDateTo(CommonConstants.TXT_TOMORROW);
			}
		}
	}

	/**
	 * 
	 * @param listToAdd
	 * @param destList
	 */
	public void addMarketsToMarketListInSortedManner(List<Market> listToAdd,
			List<Market> destList) {
		for (Market m : listToAdd) {
			addMarketToMarketListInSortedManner(m, destList);
		}
	}

	/**
	 * 
	 * @param m
	 * @param list
	 */
	public void addMarketToMarketListInSortedManner(Market m, List<Market> list) {
		boolean added = false;
		Market m2 = null, m3 = null;

		for (int i = 0; i < list.size() - 1; ++i) {
			m2 = list.get(i);
			if (m2.getId() == m.getId()) {
				list.add(i + 1, m);
				list.remove(i);
				added = true;
				break;
			}
		}

		if (added) {
			return;
		}

		for (int i = list.size() - 1; i >= 0; --i) {
			m2 = list.get(i);

			if (m.getDateFromObject().getTime() > m2.getDateFromObject()
					.getTime()) {
				list.add(i + 1, m);
			} else if (m.getDateFromObject().getTime() == m2
					.getDateFromObject().getTime()) {
				for (int j = i; j >= 0; --j) {
					m3 = list.get(j);
					if (m.getDateFromObject().getTime() == m3
							.getDateFromObject().getTime()) {
						if (m.getDateToObject().getTime() >= m3
								.getDateToObject().getTime()) {
							list.add(j + 1, m);
							added = true;
							break;
						}
					}
				}

				if (added) {
					break;
				}
			}
		}

		if (!added) {
			list.add(0, m);
		}
	}

	public boolean isLoadingMarketList() {
		return this.isLoadingMarketList;
	}

	public boolean isLoadingMarketTypeList() {
		return isLoadingMarketTypeList;
	}

	public void setLoadingMarketTypeList(boolean isLoadingMarketTypeList) {
		this.isLoadingMarketTypeList = isLoadingMarketTypeList;
	}

	public DateFormat getDateFormat() {
		return dateFormat;
	}

	public Geocoder getGeocoder() {
		return geocoder;
	}

	public void setGeocoder(Geocoder geocoder) {
		this.geocoder = geocoder;
	}

	public void showProgressDialog(final Activity activity,
			final ProgressStoppable ps) {
		AsyncTask<String, Integer, Long> asyncTask = new AsyncTask<String, Integer, Long>() {

			ProgressDialog dialog = null;

			@Override
			protected void onPreExecute() {
				dialog = new ProgressDialog(activity);
				dialog.setIndeterminate(true);
				dialog.setCancelable(true);
			}

			@Override
			protected Long doInBackground(String... params) {
				publishProgress(Integer.valueOf(1));

				while (!ps.canStopNow()) {
					try {
						Thread.sleep(500);
					} catch (InterruptedException e) {
						// TODO Auto-generated catch block
						e.printStackTrace();
					}
				}

				publishProgress(Integer.valueOf(2));

				return null;
			}

			@Override
			protected void onProgressUpdate(Integer... values) {
				Integer i = (Integer) values[0];
				if (i == 1) {
					dialog.show();
				} else {
					dialog.cancel();
				}
			}

		};

		asyncTask.execute("");
	}

	private Handler uiHandler = new Handler() {
		public void handleMessage(Message msg) {
			if (msg.what == 1) {
				if (marketListFragment != null) {
					if (marketListFragment.getListViewMarketListAdapter() != null)
						marketListFragment.getListViewMarketListAdapter()
								.notifyDataSetChanged();
				}
			}
		};
	};

	public List<MarketType> getMarketTypeList() {
		return marketTypeList;
	}

	public void setMarketTypeList(List<MarketType> marketTypeList) {
		this.marketTypeList = marketTypeList;
	}

	public List<Category> getCategoryList() {
		return categoryList;
	}

	public void setCategoryList(List<Category> categoryList) {
		this.categoryList = categoryList;
	}

	public List<Market> getMarketList() {

		if (!threadLoadMarketListDone) {

			// get size here so that the other modification the list, it will
			// not
			// affect number of items will be read here
			int size = marketList.size();
			List<Market> res = new ArrayList<Market>(size);

			for (int i = 0; i < size; ++i) {
				res.add(marketList.get(i));
			}

			return res;
		}

		return marketList;
	}

	public void setMarketList(List<Market> marketList) {
		this.marketList = marketList;
	}

	public List<Market> getBusinessMarketList() {
		if (!isLoadingBusinessMarketList) {

			// get size here so that the other modifies the list, it will not
			// affect
			// number of items will be read here
			int size = businessMarketList.size();
			List<Market> res = new ArrayList<Market>(size);

			for (int i = 0; i < size; ++i) {
				res.add(businessMarketList.get(i));
			}

			return res;
		}

		return businessMarketList;
	}

	public void setBusinessMarketList(List<Market> businessMarketList) {
		this.businessMarketList = businessMarketList;
	}

	public List<Market> getMarketListWithLoadedLocation() {
		return marketListWithLoadedLocation;
	}

	public void setMarketListWithLoadedLocation(
			List<Market> marketListWithLoadedLocation) {
		this.marketListWithLoadedLocation = marketListWithLoadedLocation;
	}

	public boolean isLoadingMarketLocation() {
		return isLoadingMarketLocation;
	}

	public void setLoadingLocation(boolean isLoadingLocation) {
		this.isLoadingMarketLocation = isLoadingLocation;
	}

	public Map<MarketType, List<Market>> getDataOrganized() {
		return dataOrganized;
	}

	public void setDataOrganized(Map<MarketType, List<Market>> dataOrganized) {
		this.dataOrganized = dataOrganized;
	}

	public Date getLastTimeLoadData() {
		return lastTimeLoadData;
	}

	public void setLastTimeLoadData(Date lastTimeLoadData) {
		this.lastTimeLoadData = lastTimeLoadData;
	}

	public void setLoadingMarketList(boolean isLoadingMarketList) {
		this.isLoadingMarketList = isLoadingMarketList;
	}

	public int getSelectedMarketTypeId() {
		return this.selectedmarketType;
	}

	public void setSelectedmarketTypeId(int selectedMarketType) {
		this.selectedmarketType = selectedMarketType;
	}

	public List<Category> getMarketCategoryList() {
		return this.categoryList;
	}

	public Market getSelectedMarketForDetailsView() {
		return selectedMarketForDetailsView;
	}

	public void setSelectedMarketForDetailsView(
			Market selectedMarketForDetailsView) {
		this.selectedMarketForDetailsView = selectedMarketForDetailsView;
	}

	public int getCurrentMarketListMode() {
		return currentMarketListMode;
	}

	public void setCurrentMarketListMode(int currentMarketListMode) {
		if (currentMarketListMode != 0)
			this.currentMarketListMode = currentMarketListMode;
	}

	public int getSelectedMaketCategory() {
		return selectedMaketCategory;
	}

	public void setSelectedMaketCategory(int selectedMaketCategory) {
		this.selectedMaketCategory = selectedMaketCategory;
	}

	public MarketDetailsFragment getMarketDetailsFragment(Market market) {
		if (marketDetailsFragment == null) {
			marketDetailsFragment = MarketDetailsFragment.newInstance(market);
//			marketDetailsFragment.setCurrentMarket(market);
		}
		return marketDetailsFragment;
	}

	public MarketDetailsFragment getMarketDetailsFragmentForTopMarkeder(
			Market market) {
		if (marketDetailsFragmentForTopMarkeder == null) {
			marketDetailsFragmentForTopMarkeder = MarketDetailsFragment.newInstance(market);
//			marketDetailsFragmentForTopMarkeder.setCurrentMarket(market);
		}
		return marketDetailsFragmentForTopMarkeder;
	}

	public MarketDetailsFragment getMarketDetailsFragmentForMap(Market market) {
		if (marketDetailsFragmentForMap == null) {
			marketDetailsFragmentForMap = MarketDetailsFragment.newInstance(market);
//			marketDetailsFragmentForMap.setCurrentMarket(market);
		}
		return marketDetailsFragmentForMap;
	}

	public MarketListFragment getMarketListFragment() {
		if (marketListFragment == null) {
			marketListFragment = new MarketListFragment();
		}
		return marketListFragment;
	}
	
	public MarketListFragment getMarketListFragmentForTopMarkeder() {
		if (marketListFragmentForTopMarkeder == null) {
			marketListFragmentForTopMarkeder = new MarketListFragment();
		}
		return marketListFragmentForTopMarkeder;
	}

	public MarketListFragment getTopMarketFragment() {
		if (topMarketFragment == null) {
			topMarketFragment = new MarketListFragment();
		}
		return topMarketFragment;
	}
	
	public void setMarketDetailsFragment(
			MarketDetailsFragment marketDetailsFragment) {
		this.marketDetailsFragment = marketDetailsFragment;
	}
	
	public MapScreenFragment getMapScreenFragment() {
		return mapScreenFragment;
	}

	public void setMapScreenFragment(MapScreenFragment mapScreenFragment) {
		this.mapScreenFragment = mapScreenFragment;
	}

	public void setCurrentSelectedTab(int tab) {
		this.currentSelectedTab = tab;
	}

	public int getCurrentSelectedTab() {
		return this.currentSelectedTab;
	}

	public OpenMarketFragment getOpenMarketFragment() {
		if (openMarketFragment == null) {
			openMarketFragment = new OpenMarketFragment();
		}
		return openMarketFragment;
	}

	public HomeScreenFragment getHomeScreenFragment() {
		if (homeScreenFragment == null) {
			homeScreenFragment = new HomeScreenFragment();
		}
		return homeScreenFragment;
	}

	public MapScreenFragmentContainer getMapScreenFragmentContainer() {
		if (mapScreenFragmentContainer == null) {
			mapScreenFragmentContainer = new MapScreenFragmentContainer();
		}
		return mapScreenFragmentContainer;
	}

	public CategoryListFragment getCategoryListFragment() {
		if (categoryListFragment == null) {
			categoryListFragment = new CategoryListFragment();
		}
		return categoryListFragment;
	}

	public Context getContext() {
		return context;
	}

	public void setContext(Context context) {
		this.context = context;
	}

	public int getSaveCurrentMarketListMode() {
		return saveCurrentMarketListMode;
	}

	public void setSaveCurrentMarketListMode(int saveCurrentMarketListMode) {
		this.saveCurrentMarketListMode = saveCurrentMarketListMode;
	}

	public Point getScreenSize() {
		return screenSize;
	}

	public void setScreenSize(int w, int h) {
		this.screenSize = new Point(w, h);
	}

	public boolean isRootFragmentOfTab() {
		return isRootFragmentOfTab;
	}

	public void setRootFragmentOfTab(boolean isRootFragmentOfTab) {
		this.isRootFragmentOfTab = isRootFragmentOfTab;
	}

	public LatLng getDeviceCurrentLocation() {
		return deviceCurrentLocation;
	}

	public void setDeviceCurrentLocation(LatLng deviceCurrentLocation) {
		this.deviceCurrentLocation = deviceCurrentLocation;
	}
}
